package org.tio.sitexxx.service.zk;

import java.util.ArrayList;
import java.util.List;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.sitexxx.service.vo.Const;
import org.tio.utils.zk.Zk;

import cn.hutool.core.util.StrUtil;

/**
 * @author tanyaowu 
 * 2016年10月19日 下午6:03:43
 */
public class ImServerNodeListener implements PathChildrenCacheListener {
	private static Logger log = LoggerFactory.getLogger(ImServerNodeListener.class);

	public static final ImServerNodeListener me = new ImServerNodeListener();

	private static List<String> imServers = null;

	/**
	 * 获取所有可用im服务器
	 * @return
	 * @author: tanyaowu
	 */
	public static List<String> getImServers() {
		if (ImServerNodeListener.imServers == null) {
			synchronized (ImServerNodeListener.class) {
				if (ImServerNodeListener.imServers == null) {
					try {
						ImServerNodeListener.imServers = Zk.getChildren(Const.ZkNode.IM_SERVERS);
					} catch (Throwable e) {
						log.error(e.toString(), e);
					}
					if (ImServerNodeListener.imServers == null) {
						ImServerNodeListener.imServers = new ArrayList<>();
					}
				}
			}
		}
		return ImServerNodeListener.imServers;
	}

	/**
	 * 该服务器是否可用
	 * @param imServer
	 * @return true: 可用, false: 不可用
	 * @author: tanyaowu
	 */
	public static boolean isAvailable(String imServer) {
		if (StrUtil.isBlank(imServer)) {
			return false;
		}
		return imServers.contains(imServer);
	}

	/**
	 * 重新获取im服务器列表
	 * @return
	 * @author: tanyaowu
	 */
	public static List<String> updateImServers() {
		synchronized (ImServerNodeListener.class) {
			try {
				ImServerNodeListener.imServers = Zk.getChildren(Const.ZkNode.IM_SERVERS);
			} catch (Throwable e) {
				log.error(e.toString(), e);
			}
			if (ImServerNodeListener.imServers == null) {
				ImServerNodeListener.imServers = new ArrayList<>();
			}
		}

		return ImServerNodeListener.imServers;

	}

	/**
	 * 
	 * @author: tanyaowu
	 */
	private ImServerNodeListener() {
	}

	/**
	 * 
	 * @param client
	 * @param event
	 * @throws Exception
	 * @author: tanyaowu
	 */
	@Override
	public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
		if (imServers == null) {
			imServers = getImServers();
		}

		PathChildrenCacheEvent.Type type = event.getType();
		if (PathChildrenCacheEvent.Type.CHILD_UPDATED != type) {
			updateImServers();
		}
	}

	/**
	 * @param args
	 * @author: tanyaowu
	 */
	public static void main(String[] args) {

	}
}
